<template>
    <div>
        子
        <!-- {{ price }} -->
        <el-input
            ref="input"
            v-model="money"
            placeholder=""
            size="normal"
            clearable
        ></el-input>
    </div>
</template>

<script>
export default {
    components: {},
    props: {
        value: {
            required: false,
        },
    },
    data() {
        return {
            // money: 0,
            symbolNum: 0,
        };
    },
    provide() {
        return {};
    },
    computed: {
        money: {
            get() {
                let value = this._.cloneDeep(this.value?.trim?.())?.toString();
                if (value === undefined || value === null || value === "") {
                    return undefined;
                }

                if (value.at(-1) == ".") {
                    return value;
                }

                let price = Number(value);
                let fixed2 = Number(price.toFixed(2));
                let price_thousand = new Intl.NumberFormat("en-us").format(
                    fixed2
                );

                let input = this.$refs.input?.$refs?.input;
                // const symbolNum = price_thousand?.length - value?.length;
                const symbolNum = price_thousand.match(/\,/g)?.length ?? 0;
                if (input) {
                    let position = input.selectionStart;

                    let diff = symbolNum - this.symbolNum;
                    this.symbolNum = symbolNum;
                    this.$nextTick(() => {
                        input.setSelectionRange(
                            position + diff,
                            position + diff
                        );
                    });
                }
                return price_thousand;
            },
            set(val) {
                let value = this._.cloneDeep(val)?.toString();

                if (value === undefined || value === null || value === "") {
                    this.$emit("input", value);
                    return;
                }
                if (value.at(-1) == ".") {
                    this.$emit("input", value);
                    return;
                }
                let [integer, decimals] = value.split(".");

                let integerNum = integer?.match(/\d/g)?.join();
                let decimalsNum = decimals?.match(/\d/g)?.join();
                let num;
                if (decimalsNum) {
                    num = `${integerNum}.${decimalsNum}`;
                } else {
                    num = `${integerNum}`;
                }
                num = num.replace(/\,/g, "");
                this.$emit("input", isNaN(num) ? 0 : num);
            },
        },
    },
    beforeDestroy() {},
    mounted() {},
    methods: {},
};
</script>

<style></style>
